﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Register.Model;
using Register.BLL;
using Register.DAL;
using System.Web.Script.Serialization;
using Register.Command;
using System.Text;
namespace RegisterWeb.Manager.SchedulingInfoManager.ashx
{
    /// <summary>
    /// SchedulingInfoManagerServer 的摘要说明
    /// </summary>
    public class SchedulingInfoManagerService : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            String action = context.Request["action"].ToString();
            if (action.Equals("list"))
            {
                int row = int.Parse(context.Request["rows"].ToString());
                int page = int.Parse(context.Request["page"].ToString());
                List<SchedulingInfo> list = new List<SchedulingInfo>();
                list = SchedulingInfoBLL.GetPagedSchedulingInfo(row, page, " SchedulingInfo_Status=1 ");

                List<SchedulingInfoJSON> json = new List<SchedulingInfoJSON>();
                foreach (SchedulingInfo SchedulingInfo in list)
                {
                    String ConfirmStatus = "";
                    if (SchedulingInfo.SchedulingInfo_ConfirmStatus == "0")
                        ConfirmStatus = "未确认";
                    if (SchedulingInfo.SchedulingInfo_ConfirmStatus == "1")
                        ConfirmStatus = "已确认";
                    if (SchedulingInfo.SchedulingInfo_ConfirmStatus == "2")
                        ConfirmStatus = "需调整";
                    json.Add(new SchedulingInfoJSON(SchedulingInfo.SchedulingInfo_ID, SchedulingInfo.Departments_ID, getDepartments(SchedulingInfo.Departments_ID), SchedulingInfo.Doctor_ID, getDoctor(SchedulingInfo.Doctor_ID), SchedulingInfo.SchedulingInfo_TimeType, getTimeType(SchedulingInfo.SchedulingInfo_TimeType), SchedulingInfo.SchedulingInfo_DayTime.ToString("yyyy-M-d"), SchedulingInfo.SchedulingInfo_OutpatientType, getOutpatientType(SchedulingInfo.SchedulingInfo_OutpatientType), SchedulingInfo.SchedulingInfo_RegisteredNumber.ToString(), ConfirmStatus, SchedulingInfo.SchedulingInfo_Status, SchedulingInfo.SchedulingInfo_AddTime.ToString(), SchedulingInfo.SchedulingInfo_Recoder, SchedulingInfo.SchedulingInfo_LastAmendTime.ToString(), SchedulingInfo.SchedulingInfo_LastAmendPerson));
                }

                SchedulingInfoListJSON SchedulingInfoListJSON = new SchedulingInfoListJSON();
                SchedulingInfoListJSON.total = SchedulingInfoBLL.GetSchedulingInfoCount(null);
                SchedulingInfoListJSON.rows = json;

                JavaScriptSerializer jss = new JavaScriptSerializer();
                context.Response.Write(jss.Serialize(SchedulingInfoListJSON));
            }
          
            else if (action.Equals("add"))
            {

                int type = int.Parse(context.Request["Type"]);
                SchedulingInfoBLL.DeleteSchedulingInfo("1");
                //获得部门ID和Name                
                List<DepartmentsInfo> DepartmentsInfo=new List<Register.Model.DepartmentsInfo>();
                DepartmentsInfo=DoctorInfoBLL.GetDepartmentsList();
                foreach(DepartmentsInfo Departments in DepartmentsInfo)
                {
                    //获得每个部门的医生在职信息
                    //按在职时间排序
                    List<DoctorWorkDay> DoctorWorkDay = new List<Register.Model.DoctorWorkDay>();
                    DoctorWorkDay = DoctorWorkDayBLL.GetDepartments_ID(Departments.Departments_ID);
                    //根据科室获得医生信息
                    List<DoctorInfo> DoctorInfo = new List<Register.Model.DoctorInfo>();
                    String where = "Departments_ID = '" + Departments.Departments_ID + "'";
                    DoctorInfo = SchedulingInfoBLL.GetDoctorInfo(where);
                    //枚举，从时间往后推，填补每天安排，如果有多个选择，根据权值
                    DateTime now = DateTime.Now;
                    int j=0;
                    int length = DoctorWorkDay.Count;
                    for (int i = 0; i < 6*type; i++)
                    {
                        now = now.AddDays(1);
                        //权值
                        int[] Value = { -1, -1, -1 };//上午，下午，全天
                        int[] num = new int[3];
                        //查找与时间相同的在职医生
                        if (j < length)
                        {
                            while (now.Day == DoctorWorkDay[j].DoctorWorkDay_DayTime.Day && now.Month == DoctorWorkDay[j].DoctorWorkDay_DayTime.Month)
                            {
                                int count = GetSchedulingType(DoctorWorkDay[j]);//获得时间类型
                                int Value_now = GetValue(DoctorWorkDay[j].Doctor_ID, DoctorInfo);//获得医生权值
                                //权值最小的医生
                                if (Value[count] == -1)
                                {
                                    Value[count] = Value_now;
                                    num[count] = j;
                                }
                                else if (Value_now < Value[count])
                                {
                                    Value[count] = Value_now;
                                    num[count] = j;
                                }
                                j++;
                                if (j >= length)
                                    break;
                            }
                            //选择最佳的方案
                            int choice = 0;//方案1：选择两个半天  2：选择一个全天

                            if (Value[0] == -1 || Value[1] == -1)
                            { choice = 2; }
                            if (Value[2] == -1)
                            { choice = 1; }
                            if ((Value[0] != -1 && Value[1] != -1 && Value[2] != -1) && (Value[0] + Value[1] <= Value[2]))
                            { choice = 1; }
                            if ((Value[0] != -1 && Value[1] != -1 && Value[2] != -1) && (Value[0] + Value[1] > Value[2]))
                            { choice = 2; }

                            if (choice == 1)//方案1
                            {
                                //选择后的医生增加权值
                                foreach (DoctorInfo a in DoctorInfo)
                                {
                                    if (a.Doctor_ID.Equals(DoctorWorkDay[num[0]].Doctor_ID))
                                    {
                                        a.Value++;
                                    }
                                    if (a.Doctor_ID.Equals(DoctorWorkDay[num[1]].Doctor_ID))
                                    {
                                        a.Value++;
                                    }
                                }
                                //添加信息
                                SetSchedulingInfo(DoctorWorkDay[num[0]], DoctorInfo);
                                SetSchedulingInfo(DoctorWorkDay[num[1]], DoctorInfo);
                            }
                            if (choice == 2)
                            {
                                //选择后的医生增加权值
                                foreach (DoctorInfo a in DoctorInfo)
                                {
                                    if (a.Doctor_ID.Equals(DoctorWorkDay[num[2]].Doctor_ID))
                                    {
                                        a.Value += 2;
                                    }
                                }
                                //添加信息
                                SetSchedulingInfo(DoctorWorkDay[num[2]], DoctorInfo);
                            }
                        }
                    }
                }
            }
            //else if (action.Equals("edit"))
            //{
            //    SchedulingInfo SchedulingInfo = new SchedulingInfo();
            //    SchedulingInfo.SchedulingInfo_ID = context.Request["ID"];
            //    SchedulingInfo.Doctor_ID = context.Request["Doctor_Name"];
            //    SchedulingInfo.SchedulingInfo_TimeType = context.Request["Type"];
            //    SchedulingInfo.SchedulingInfo_DayTime = DateTime.Parse(context.Request["DayTime"]);
            //    JavaScriptSerializer jss = new JavaScriptSerializer();
            //    context.Response.Write(jss.Serialize(new message(SchedulingInfoBLL.UpdateSchedulingInfo(SchedulingInfo), "编辑成功！")));

            //}

            //else if (action.Equals("search"))
            //{
            //    string TimeType = context.Request["TimeType"];
            //    string Doctor_ID = context.Request["Doctor_ID"];
            //    string Begin = context.Request["Begin"];
            //    string End = context.Request["End"];
            //    SchedulingInfoListJSON SchedulingInfoListJSON = new SchedulingInfoListJSON();
            //    SchedulingInfoListJSON.rows = new List<SchedulingInfoJSON>();

            //    int row = int.Parse(context.Request["rows"].ToString());
            //    int page = int.Parse(context.Request["page"].ToString());

            //    StringBuilder strBuilder = new StringBuilder();
            //    strBuilder.Append(" SchedulingInfo_State='1' ");
            //    if (!String.IsNullOrEmpty(Doctor_ID))
            //    {
            //        strBuilder.Append(" and  Doctor_ID='").Append(Doctor_ID).Append("' ");
            //    }
            //    if (!String.IsNullOrEmpty(TimeType))
            //    {
            //        strBuilder.Append(" and  SchedulingInfo_TimeType='").Append(TimeType).Append("' ");
            //    }
            //    if (!(String.IsNullOrEmpty(Begin) || String.IsNullOrEmpty(End)))
            //    {
            //        strBuilder.Append(" and SchedulingInfo_DayTime  Between '").Append(Begin).Append("' and '").Append(End).Append("'");
            //    }
            //    List<Register.Model.SchedulingInfo> list = SchedulingInfoBLL.GetPagedSchedulingInfo(row, page, strBuilder.ToString());
            //    SchedulingInfoListJSON.total = SchedulingInfoBLL.GetSchedulingInfoCount(strBuilder.ToString());


            //    foreach (Register.Model.SchedulingInfo SchedulingInfo in list)
            //    {
            //        SchedulingInfoListJSON.rows.Add(new SchedulingInfoJSON(SchedulingInfo.SchedulingInfo_ID, SchedulingInfo.Doctor_ID, getDoctor(SchedulingInfo.Doctor_ID), SchedulingInfo.SchedulingInfo_TimeType, getTimeType(SchedulingInfo.SchedulingInfo_TimeType), SchedulingInfo.SchedulingInfo_DayTime.ToString(), SchedulingInfo.SchedulingInfo_AddTime.ToString(), SchedulingInfo.SchedulingInfo_Recoder, SchedulingInfo.SchedulingInfo_State));
            //    }


            //    JavaScriptSerializer jss = new JavaScriptSerializer();
            //    context.Response.Write(jss.Serialize(SchedulingInfoListJSON));
            //}
            //else if (action.Equals("check"))
            //{
            //    string name = context.Request["ID"];
            //    if (AdminInfoBLL.Exists(name))
            //    {
            //        context.Response.Write("ok");
            //    }
            //    else
            //    {
            //        context.Response.Write("no");
            //    }
            //}
            //else if (action.Equals("Type"))
            //{
            //    List<Parameter> list;
            //    JavaScriptSerializer jss = new JavaScriptSerializer();

            //    list = ParamterHelper.GetParametersByType("Scheduling_Time");
            //    context.Response.Write(jss.Serialize(list));
            //}
            //else if (action.Equals("Name"))
            //{
            //    List<DoctorInfo> list;
            //    JavaScriptSerializer jss = new JavaScriptSerializer();

            //    list = SchedulingInfoBLL.GetDoctorInfo();
            //    context.Response.Write(jss.Serialize(list));
            //}

        }
        //根据ID获得时间类型
        int GetSchedulingType(DoctorWorkDay DoctorWorkDay)
        {
            int count=0;
            if (DoctorWorkDay.DoctorWorkDay_TimeType.Equals("ST01"))
            {
                count = 0;
            }
            if (DoctorWorkDay.DoctorWorkDay_TimeType.Equals("ST02"))
            {
                count = 1;
            }
            if (DoctorWorkDay.DoctorWorkDay_TimeType.Equals("ST03"))
            {
                count = 2;
            }
            return count;
        }
        //获得医生权值
        int GetValue(String Doctor_ID, List<DoctorInfo> DoctorInfo)
        {
            int value = 0;
            foreach (DoctorInfo a in DoctorInfo)
            {
                if (a.Doctor_ID.Equals(Doctor_ID))
                {
                        value = a.Value;
                }
            }
            return value; 
        }
        void SetSchedulingInfo(DoctorWorkDay DoctorWorkDay, List<DoctorInfo> DoctorInfo)
        {
            foreach (DoctorInfo a in DoctorInfo)
            {
                if (a.Doctor_ID.Equals(DoctorWorkDay.Doctor_ID))
                {
                    SchedulingInfo SchedulingInfo = new SchedulingInfo();
                    SchedulingInfo.SchedulingInfo_ID = DataIDHelper.GetDataID("SchedulingInfo_ID");
                    SchedulingInfo.Departments_ID = DoctorWorkDay.DoctorWorkDay_Departments_ID;
                    SchedulingInfo.Doctor_ID = a.Doctor_ID;
                    SchedulingInfo.SchedulingInfo_TimeType = DoctorWorkDay.DoctorWorkDay_TimeType;
                    SchedulingInfo.SchedulingInfo_OutpatientType = a.Doctor_Type;
                    SchedulingInfo.SchedulingInfo_RegisteredNumber = 5;
                    SchedulingInfo.SchedulingInfo_ConfirmStatus = "0";
                    SchedulingInfo.SchedulingInfo_Recoder = "admin";///////////////////////////////////////////////////////////////////////////记录
                    SchedulingInfo.SchedulingInfo_AddTime = DateTime.Now;
                    SchedulingInfo.SchedulingInfo_DayTime = DoctorWorkDay.DoctorWorkDay_DayTime;
                    SchedulingInfo.SchedulingInfo_Status = "1";
                    SchedulingInfo.SchedulingInfo_LastAmendTime = DateTime.Now;
                    SchedulingInfo.SchedulingInfo_LastAmendPerson = "admin";

                    SchedulingInfoBLL.AddSchedulingInfo(SchedulingInfo);
                    break;
                }
            }
        }


        //获得时间类型
        public String getTimeType(String TimeType)
        {
            String TextTimeType = "";
            List<Parameter> list;
            JavaScriptSerializer jss = new JavaScriptSerializer();

            list = ParamterHelper.GetParametersByType("Scheduling_Time");
            foreach (Parameter parameter in list)
            {
                if (parameter.SystemParameter_ID == TimeType)
                    TextTimeType = parameter.SystemParameter_Name;
            }
            return TextTimeType;
        }
        //获得医生姓名
        public String getDoctor(String Doctor_ID)
        {
            String DoctorName = "";
            DoctorInfo list;
            JavaScriptSerializer jss = new JavaScriptSerializer();

            list = DoctorInfoBLL.GetDoctorInfo(Doctor_ID);
            DoctorName = list.Doctor_Name;
            return DoctorName;
        }
        public String getDepartments(String DepartmentsID)
        {
            String Name="";
            List<DepartmentsInfo> DepartmentsInfo = new List<Register.Model.DepartmentsInfo>();
            DepartmentsInfo = DoctorInfoBLL.GetDepartmentsList();
            foreach (DepartmentsInfo a in DepartmentsInfo)
            {
                if (a.Departments_ID == DepartmentsID)
                    Name = a.Departments_Name;
            }
            return Name;
        }
        public String getOutpatientType(String OutpatientType)
        {
            String Doctor_Position = "";
            List<Parameter> list;
            JavaScriptSerializer jss = new JavaScriptSerializer();

            list = ParamterHelper.GetParametersByType("Doctor_Position");
            foreach (Parameter parameter in list)
            {
                if (parameter.SystemParameter_ID == OutpatientType)
                    Doctor_Position = parameter.SystemParameter_Name;
            }
            return Doctor_Position;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    class message
    {
        public message(bool success, string msg)
        {
            this.msg = msg;
            this.success = success;
        }
        public bool success { get; set; }
        public string msg { get; set; }
    }

    class SchedulingInfoListJSON
    {

        public int total { get; set; }
        public List<SchedulingInfoJSON> rows { get; set; }

    }

    class SchedulingInfoJSON
    {
        public String ID { get; set; }
        public String Departments_ID { get; set; }
        public String Departments_Name { get; set; }
        public String Doctor_ID { get; set; }
        public String Doctor_Name { get; set; }
        public String TimeType { get; set; }
        public String TextTimeType { get; set; }
        public String DayTime { get; set; }
        public String OutpatientType { get; set; }
        public String TextOutpatientType { get; set; }
        public String RegisteredNumber { get; set; }
        public String ConfirmStatus { get; set; }
        public String State { get; set; }
        public String AddTime { get; set; }
        public String Recoder { get; set; }
        public String LastAmendTime { get; set; }
        public String LastAmendPerson { get; set; }


        public SchedulingInfoJSON(String ID, String Departments_ID, String Departments_Name, String Doctor_ID, String Doctor_Name,String TimeType, String TextTimeType, String DayTime, String OutpatientType, String TextOutpatientType,String RegisteredNumber,String ConfirmStatus, String State, String AddTime, String Recoder, String LastAmendTime, String LastAmendPerson)
        {
            this.ID = ID;
            this.Departments_ID = Departments_ID;
            this.Departments_Name = Departments_Name;
            this.Doctor_ID = Doctor_ID;
            this.Doctor_Name = Doctor_Name;
            this.TimeType = TimeType;
            this.TextTimeType = TextTimeType;
            this.DayTime = DayTime;
            this.OutpatientType = OutpatientType;
            this.TextOutpatientType = TextOutpatientType;
            this.RegisteredNumber = RegisteredNumber;
            this.ConfirmStatus = ConfirmStatus;
            this.State = State;
            this.AddTime = AddTime;
            this.Recoder = Recoder;
            this.LastAmendTime = LastAmendTime;
            this.LastAmendPerson = LastAmendPerson;
        }

    }
}